#pragma once
#include <pthread.h>
#include <string>
#include <functional>
#include <iostream>
class thread
{
public:
    typedef std::function<void *(void *)> func_t;
    typedef enum
    {
        NEW = 0,
        RUNING,
        EXITED
    } status;
    thread(int num, func_t func, void *args) : _tid(0), _args(args), _func(func), _status(NEW)
    {
        std::string name = "thread-" + std::to_string(num);
        _name = name;
    }
    pthread_t getTid()
    {
        if (_status == RUNING)
        {
            return _tid;
        }
        else
        {
            return 0;
        }
    }
    std::string getName()
    {
        return _name;
    }
    status getStatus()
    {
        return _status;
    }
    // 因为类内成员函数自带this指针所以要加static
    static void *runHelper(void *args)
    {
        thread *td = static_cast<thread *>(args);
        (*td)();
        return nullptr;
    }
    void operator()()
    {
        if (_func != nullptr)
        {
            // 将_args作为参数传入
            _func(_args);
        }
    }
    void run()
    {
        int n = pthread_create(&_tid, nullptr, runHelper, this);
        if (n != 0)
        {
            exit(1);
        }
        _status = RUNING;
    }
    void join()
    {
        int n = pthread_join(_tid, nullptr);
        if (n != 0)
        {
            std::cerr << "main pthread join pthread" << _name << "error" << '\n';
            return;
        }
        _status = EXITED;
    }
    ~thread()
    {
    }

private:
    pthread_t _tid;
    std::string _name;
    void *_args;
    func_t _func;   // 线程执行的回调
    status _status; // 线程运行状态
};